﻿/* $RCSFile: SelListBox.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/SelListBox.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Diagnostics;

using Telerik.Web.UI;

using Trace2    =    System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{
    #region Local TraceSwitch for SelListBox
    public class SelListBoxTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("SelListBoxTrace","Trace Switch for SelListBox");
	}
	#endregion Local TraceSwitch for SelListBox

    [ToolboxData("<{0}:SelListBox runat=server></{0}:SelListBox>")]
    public class SelListBox : CompositeControl
    {
        RadListBox LbSource     =   null;
        RadListBox LbDest       =   null;
        const string SelListBoxSelectedValueStr =   "SelListBoxSelectedValue";

        Unit _LbHeight          =   Unit.Empty;
        public Unit LbHeight
        {
             get { return _LbHeight; }
             set { _LbHeight    =   value; }
        }

        Unit _LbWidth           =   Unit.Empty;
        public Unit LbWidth
        {
             get { return _LbWidth; }
             set { _LbWidth    =   value; }
        }

        bool _SideBySide    =   true;
        public bool SideBySide
        {
             get { return _SideBySide; }
             set { _SideBySide  =   value; }
        }


        public string DataValueField
		{
			get
			{
                object ob   =   ViewState["DataValueField"];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
			}
			set
			{
				ViewState["DataValueField"] = value;
			}
		}

        public string DataTextField
		{
			get
			{
                object ob   =   ViewState["dataTextField"];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
			}
			set
			{
				ViewState["dataTextField"] = value;
			}
		}

        object _DataSource  =   null;
        public object DataSource
        {
             get { return _DataSource; }
             set { _DataSource  =   value; }
        }

        public override void DataBind()
        {
            if (SelListBoxTrace.Sw.TraceVerbose)
                Trace.WriteLine("[V]SelListBox DataBind BEG.", SelListBoxTrace.Sw.Info);
            OnDataBinding(EventArgs.Empty);
            EnsureChildControls();
            LbSource.DataSource        =   DataSource;
            LbSource.DataTextField     =   DataTextField;
            LbSource.DataValueField    =   DataValueField;
            LbDest.Items.Clear();
            DataBindChildren();
            if (SelListBoxTrace.Sw.TraceVerbose)
                Trace.WriteLine("[V]SelListBox DataBind END.", SelListBoxTrace.Sw.Info);
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }
        
        /// <summary>
        /// Ctor
        /// </summary>
        public SelListBox()
		{
            if (SelListBoxTrace.Sw.TraceVerbose)
                Trace.WriteLine("[V]SelListBox Ctor Called.", SelListBoxTrace.Sw.Info);
        }

        void AppendItem(RadListBoxItem nd,StringBuilder sb)
        {
            if ( SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox AppendItem BEG nd.Text: '{0}', nd.Value: '{1}'.",nd.Text,nd.Value),SelListBoxTrace.Sw.Info);
            if ( nd.Value == string.Empty )
                    sb.AppendFormat("{0};",nd.Text);
            else    sb.AppendFormat("{0};",nd.Value);
        }

        void SetSelection()
        {
            string selNodes     =   string.Empty;
            object ob           =   ViewState[SelListBoxSelectedValueStr];
            if (ob != null)
                selNodes        =   (string)ob;
            if ( SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox SetSelection BEG selNodes: {0}",selNodes),SelListBoxTrace.Sw.Info);
            string[] aNode      =   selNodes.Split(new char[] { ';' },StringSplitOptions.RemoveEmptyEntries);
            RadListBoxItem nd1  =   null;
            List<RadListBoxItem> lst    =   new List<RadListBoxItem>();
            foreach (string ndtxt in aNode)
            {
                nd1             =   LbSource.FindItemByValue(ndtxt);
                if ( SelListBoxTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox SetSelection ndtxt: {0}, found: {1}",ndtxt,(nd1 != null)),SelListBoxTrace.Sw.Info);
                if ( nd1 == null ) // value not found, try text
                    nd1         =   LbSource.FindItemByText(ndtxt);
                if ( nd1 != null )
                    lst.Add(nd1);
            }
            lst.Reverse();
            if ( lst.Count > 0 )
                LbSource.Transfer(lst,LbSource,LbDest);
            if ( SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox SetSelection END LbDest.Items.Count: {0}",LbDest.Items.Count),SelListBoxTrace.Sw.Info);
        }

        public string SelectedValue
        {
            get
            {
                if ( SelListBoxTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox SelectedValue GET BEG ChildControlsCreated: {0}.",ChildControlsCreated),SelListBoxTrace.Sw.Info);
                string sel                  =   string.Empty;
                if (ChildControlsCreated)
                {
                    if (LbDest.Items.Count > 0  )
                    {
                        StringBuilder sb    =   new StringBuilder();
                        foreach (RadListBoxItem n in LbDest.Items)
                            AppendItem(n, sb);
                        sel                 =   sb.ToString();
                        ViewState[SelListBoxSelectedValueStr] = sel;
                    }
                }
                if ( string.IsNullOrEmpty(sel) )
                {
                    object ob               =   ViewState[SelListBoxSelectedValueStr];
                    if ( ob != null )
                        sel                 =    (string)ob;
                }
                if ( SelListBoxTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox SelectedValue GET END SelectedValue: '{0}'",sel),SelListBoxTrace.Sw.Info);
                return sel;
            }
            set
            {
                if ( SelListBoxTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox SelectedValue SET ChildControlsCreated: {0}, value: '{1}'",ChildControlsCreated,value),SelListBoxTrace.Sw.Info);
                ViewState[SelListBoxSelectedValueStr] =   value;
                if (ChildControlsCreated)
                {
                    if (LbDest.Items.Count > 0)
                        LbDest.Items.Clear();
                }
            }
        }

        public void LoadContentFile(string file)
        {
            if ( SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox LoadContentFile BEG file: {0}",file),SelListBoxTrace.Sw.Info);
            EnsureChildControls();
            LbSource.LoadContentFile(file);
            if ( SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox LoadContentFile END file: {0}",file),SelListBoxTrace.Sw.Info);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose || SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SelListBox Render BEG.",(WebControlsTraceSwitch.Sw.TraceVerbose) ? WebControlsTraceSwitch.Sw.Info:SelListBoxTrace.Sw.Info);
            if ( DesignMode )
                EnsureChildControls();
            try
            {
                base.Render(writer);
            }
            catch (Exception ex)
            {
                if ( WebControlsTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]SelListBox Render ex: {0}",ex),(WebControlsTraceSwitch.Sw.TraceVerbose) ? WebControlsTraceSwitch.Sw.Info:SelListBoxTrace.Sw.Info);
                throw;
            }
            if ( WebControlsTraceSwitch.Sw.TraceVerbose || SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SelListBox Render END.",(WebControlsTraceSwitch.Sw.TraceVerbose) ? WebControlsTraceSwitch.Sw.Info:SelListBoxTrace.Sw.Info);
       }


        protected override void CreateChildControls()
        {
            if ( SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SelListBox CreateChildControls BEG.",SelListBoxTrace.Sw.Info);
            ClearChildViewState();
            Controls.Clear();
            HtmlGenericControl  div1        =   new HtmlGenericControl("div");
            if ( SideBySide )
                div1.Style.Add(HtmlTextWriterStyle.Width,"49%");
            else
            {
                if ( LbWidth != Unit.Empty )
                        div1.Style.Add(HtmlTextWriterStyle.Width,LbWidth.ToString());
                else    div1.Style.Add(HtmlTextWriterStyle.Width,"100%");
            }
            div1.Style.Add( HtmlTextWriterStyle.Position,"relative");
            div1.Style.Add( "float","left");
            LbSource                        =   new RadListBox();
            LbSource.ID                     =   "RadLstSource";
            LbSource.Height                 =   LbHeight;
            LbSource.Width                  =   new Unit(100,UnitType.Percentage);
            
            LbSource.EnableDragAndDrop      =   true;
            LbSource.AllowReorder           =   true;
            LbSource.AllowDelete            =   false;
            LbSource.CausesValidation       =   false;
            LbSource.AllowTransfer          =   true;
            LbSource.AllowTransferOnDoubleClick=   true;
            LbSource.AutoPostBack           =   false;
            LbSource.AutoPostBackOnTransfer =   false;
            LbSource.AutoPostBackOnReorder  =   false;
            LbSource.SelectionMode          =   ListBoxSelectionMode.Multiple;
            LbSource.TransferMode           =   ListBoxTransferMode.Move;
            LbSource.ButtonSettings.Position=   ListBoxButtonPosition.Right;
            LbSource.ButtonSettings.ShowTransferAll =   true;
            div1.Controls.Add(LbSource);

            HtmlGenericControl  div2        =   new HtmlGenericControl("div");
            if ( SideBySide )
                div2.Style.Add(HtmlTextWriterStyle.Width,"49%");
            else
            {
                if ( LbWidth != Unit.Empty )
                        div2.Style.Add(HtmlTextWriterStyle.Width,LbWidth.ToString());
                else    div2.Style.Add(HtmlTextWriterStyle.Width,"100%");
            }
            div2.Style.Add( HtmlTextWriterStyle.Position,"relative");
            if ( SideBySide )
                    div2.Style.Add( "float","right");
            else    div2.Style.Add( "float","left");
            LbDest                          =   new RadListBox();
            LbDest.ID                       =   "RadLstDest";
            LbDest.Height                   =   LbHeight;
            LbDest.Width                    =   new Unit(100,UnitType.Percentage);
            LbDest.EnableDragAndDrop        =   true;
            LbDest.CausesValidation         =   false;
            LbDest.AllowReorder             =   true;
            LbDest.AllowDelete              =   false;
            LbDest.AutoPostBack             =   false;
            LbDest.AutoPostBackOnTransfer   =   false;
            LbDest.AutoPostBackOnReorder    =   false;
            LbDest.SelectionMode            =   ListBoxSelectionMode.Multiple;
            
            LbSource.TransferToID           =   LbDest.ID;

            div2.Controls.Add(LbDest);
            Controls.Add(div1);
            Controls.Add(div2);
            ChildControlsCreated            =   true;
            if ( SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SelListBox CreateChildControls END.",SelListBoxTrace.Sw.Info);
        }

        protected override void OnPreRender(EventArgs e)
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose || SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SelListBox OnPreRender BEG IsPostBack: {0}", Page.IsPostBack), (WebControlsTraceSwitch.Sw.TraceVerbose) ? WebControlsTraceSwitch.Sw.Info:SelListBoxTrace.Sw.Info);
            SetSelection();
            // to position inside elements side by side
            if ( this.Style[HtmlTextWriterStyle.Position] == null )
                Style.Add( HtmlTextWriterStyle.Position,"relative");

            LbSource.Height     =   LbHeight;
            LbDest.Height       =   LbHeight;
            base.OnPreRender(e);
            if ( WebControlsTraceSwitch.Sw.TraceVerbose || SelListBoxTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SelListBox OnPreRender END.", (WebControlsTraceSwitch.Sw.TraceVerbose) ? WebControlsTraceSwitch.Sw.Info:SelListBoxTrace.Sw.Info);
        }

        protected override void OnInit(EventArgs e)
        {
            EnsureChildControls();
            base.OnInit(e);
        }
   }
}
